/**
 *  This file is part of MunchLevel.
 *
 *  MunchLevel is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MunchLevel is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MunchLevel.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.munchlevel;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.view.Display;
import android.view.MenuItem;
import android.view.WindowManager;

import com.munchlevel.util.ThemeManager;
import com.munchlevel.util.Themeable;

public abstract class BaseActivity extends FragmentActivity implements Themeable, OnSharedPreferenceChangeListener {

	public static final int ACTION_PREFERENCES = 0;

	private PowerManager.WakeLock wl;

	private ThemeManager themeManager;

	public BaseActivity() {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		themeManager = new ThemeManager(this);

		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		pref.registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.settings) {
			startActivityForResult(new Intent(this, MyPreferenceActivity.class), ACTION_PREFERENCES);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#
	 * onSharedPreferenceChanged(android.content.SharedPreferences,
	 * java.lang.String)
	 */
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

		// wakelock
		if (key == null || MyPreferenceActivity.KEY_WAKE_LOCK.equals(key)) {
			if (sharedPreferences.getBoolean(MyPreferenceActivity.KEY_WAKE_LOCK, true)) {

				if (wl == null) {

					if (wl == null) {
						PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
						wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, MunchLevelApplication.TAG);
					}

					if (!wl.isHeld()) {
						wl.acquire();
					}
				}
			} else {
				if (wl != null) {
					wl.release();
					wl = null;
				}
			}
		}

		// fullscreen
		if (key == null || MyPreferenceActivity.KEY_FULLSCREEN.equals(key)) {
			boolean visible = sharedPreferences.getBoolean(MyPreferenceActivity.KEY_FULLSCREEN, true);
			updateFullscreenStatus(visible);
		}

		// theme
		if (key == null || MyPreferenceActivity.KEY_THEME.equals(key)) {
			themeManager.applyTheme(this);
		}
	}

	public int getScreenOrientation() {

		Configuration config = getResources().getConfiguration();
		int orientation = config.orientation;

		// Sometimes you may get undefined orientation Value is 0
		// simple logic solves the problem compare the screen
		// X,Y Co-ordinates and determine the Orientation in such cases
		if (orientation == Configuration.ORIENTATION_UNDEFINED) {

			Display getOrient = getWindowManager().getDefaultDisplay();
			orientation = getOrient.getOrientation();

			if (orientation == Configuration.ORIENTATION_UNDEFINED) {
				// if height and widht of screen are equal then
				// it is square orientation
				if (getOrient.getWidth() == getOrient.getHeight()) {
					orientation = Configuration.ORIENTATION_SQUARE;
				} else { // if widht is less than height than it is portrait
					if (getOrient.getWidth() < getOrient.getHeight()) {
						orientation = Configuration.ORIENTATION_PORTRAIT;
					} else { // if it is not any of the above it will defineitly
								// be landscape
						orientation = Configuration.ORIENTATION_LANDSCAPE;
					}
				}
			}
		}
		return orientation; // return value 1 is portrait and 2 is Landscape
							// Mode
	}

	public void resetTheme() {
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);

		Editor editor = pref.edit();
		editor.putString(MyPreferenceActivity.KEY_THEME, ThemeManager.DEFAULT_THEME);
		editor.commit();
		applyTheme();
	}

	@Override
	public abstract boolean applyTheme();

	protected void updateFullscreenStatus(boolean bUseFullscreen) {
		if (bUseFullscreen) {
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		} else {
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}

		getWindow().getDecorView().requestLayout();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPostCreate(android.os.Bundle)
	 */
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		onSharedPreferenceChanged(PreferenceManager.getDefaultSharedPreferences(this), null);
	}

	@Override
	protected void onResume() {

		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		if (pref.getBoolean(MyPreferenceActivity.KEY_WAKE_LOCK, true)) {

			if (wl == null) {
				PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
				wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, MunchLevelApplication.TAG);
			}

			if (!wl.isHeld()) {
				wl.acquire();
			}
		}
		super.onResume();
	}

	protected void onDestroy() {
		if (wl != null) {
			wl.release();
			wl = null;
		}

		themeManager.close();

		super.onDestroy();
	}

}
